<template>
  <!-- 现场勘查-任务详情 -->
  <div class="contract-detail">
    <div class="app-content-container">
      <el-card>
        <!------------------------------基本信息------------------------------------>
        <div class="form-card-title">
          <el-col :span="22">
            <span>基本信息</span>
          </el-col>
          <el-col :span="2" class="text-right">
            <el-button
              type="primary"
              @click="handleContract"
              v-if="!isDisabled"
            >
              确认
            </el-button>
          </el-col>
        </div>

        <div class="form-card-content">
          <el-form
            label-position="top"
            label-width="80px"
            ref="form"
            :model="form"
            :rules="rules"
            :disabled="isDisabled"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="合同期限" prop="dateRange">
                  <el-date-picker
                    v-model="form.dateRange"
                    size="small"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input v-model="form.contractNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同名称" prop="name">
                  <el-input v-model="form.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同单位" prop="signUnit">
                  <el-select v-model="form.signUnit" filterable>
                    <el-option
                      v-for="item in companyOptions"
                      :key="item.companyName"
                      :label="item.companyName"
                      :value="item.companyName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!------------------------------工程量------------------------------------>
        <div class="form-card-title">
          <el-col :span="20">
            <span>工程量</span>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-button type="primary" @click="uploadExcel" v-if="!isDisabled">
              导入
            </el-button>
            <el-button
              type="primary"
              @click="importTemplate"
              v-if="!isDisabled"
            >
              下载模版
            </el-button>
          </el-col>
        </div>
        <div class="form-card-content">
          <el-table v-loading="loading" :data="priceList">
            <el-table-column
              prop="rowNumber"
              label="序号"
              align="center"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="projectNo"
              label="项目编号"
              min-width="100"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="projectName"
              label="项目名称"
              min-width="150"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="unit"
              label="单位"
              min-width="100"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="全费用合同单价"
              width="250"
              align="center">
              <template slot-scope="scope">
                <span>{{ (scope.row.price / 1) | rounding }}</span>
              </template>
            </el-table-column>
          </el-table>

          <Pagination
            v-show="total > 0"
            :total="total"
            :current.sync="queryParams.currPage"
            :size.sync="queryParams.pageSize"
            @pagination="getPriceList"
            v-if="oper === 'add'"
          />

          <Pagination
            v-show="total > 0"
            :total="total"
            :current.sync="queryParams.currPage"
            :size.sync="queryParams.pageSize"
            @pagination="getPriceListServer"
            v-if="oper === 'update' && !form.priceAll"
          />

          <Pagination
            v-show="total > 0"
            :total="total"
            :current.sync="queryParams.currPage"
            :size.sync="queryParams.pageSize"
            @pagination="getPriceList"
            v-if="oper === 'update' && form.priceAll"
          />

          <Pagination
            v-show="total > 0"
            :total="total"
            :current.sync="queryParams.currPage"
            :size.sync="queryParams.pageSize"
            @pagination="getPriceListServer"
            v-if="oper === 'detail'"
          />
        </div>
      </el-card>
    </div>

    <!-- 合同量导入对话框 -->
    <el-dialog
      title="工程量导入"
      :visible.sync="upload.open"
      width="440px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitExcelFileForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const operArr = ['add', 'update', 'detail']
  import {
    queryContractPriceList,
    importTemplate,
  } from '@/api/system/contract-price'
  import {
    addContract,
    updateContract,
    getContract,
  } from '@/api/system/contract'
  import {allCompany} from '@/api/system/company'
  import {getToken} from '@/utils/auth'

  export default {
    name: 'ContractDetail',
    data() {
      return {
        // 全局禁用标志
        isDisabled: false,
        // 操作类型 [修改 详情 新增]
        oper: '',
        // 合同id
        contractId: '',
        companyOptions: [],
        form: {
          dateRange: [],
          contractNo: undefined,
          name: undefined,
          signUnit: undefined,
          // 零时数据
          priceAll: [],
        },
        rules: {
          dateRange: [
            {required: true, message: '请选择合同期限', trigger: 'change'}
          ],
          contractNo: [
            {required: true, message: '请输入合同编号', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入合同名称', trigger: 'blur'},
            {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
          ],
          signUnit: [
            {required: true, message: '请选择合同单位', trigger: 'change'}
          ]

        },
        loading: false,
        priceList: [],
        // 总条数
        total: 0,
        queryParams: {
          contractId: undefined,
          currPage: 1,
          pageSize: 10,
        },
        // 合同工程量导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: 'Bearer ' + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/sys/importContractPriceData',
        },
      }
    },
    mounted() {
      let oper = this.$route.params.oper
      if (operArr.indexOf(oper) !== -1) {
        this.oper = oper
        if (oper === 'add') {
          this.getAllCompany()
        } else if (oper === 'update') {
          this.contractId = this.$route.params.id
          this.queryParams.contractId = this.$route.params.id
          this.getContract()
          this.getAllCompany()
          this.getPriceListServer()
        } else if (oper === 'detail') {
          this.isDisabled = true
          this.contractId = this.$route.params.id
          this.queryParams.contractId = this.$route.params.id
          this.getContract()
          this.getAllCompany()
          this.getPriceListServer()
        }
      }
    },
    methods: {
      // 获取合同单位下拉选项
      getAllCompany() {
        allCompany().then((response) => {
          this.companyOptions = response.data
        })
      },
      // 获取合同信息
      getContract() {
        getContract({id: this.contractId}).then((response) => {
          let {
            contractId,
            contractNo,
            contractName,
            signUnit,
            contractSTime,
            contractETime,
          } = response.data
          let contract = {
            contractId: contractId,
            dateRange: [contractSTime, contractETime],
            contractNo: contractNo,
            name: contractName,
            signUnit: signUnit,
          }
          this.form = contract
        })
      },
      // 获取合同下工程量
      getPriceListServer() {
        queryContractPriceList(this.queryParams).then((response) => {
          // TODO 待完成 合同工作量 合同单位下拉选择
          this.priceList = response.data
          this.total = response.page.total
        })
      },
      // 下载工程量导入模板
      importTemplate() {
        importTemplate().then((response) => {
          this.downloadExcel(response.msg)
        })
      },
      // 显示上传弹出框
      uploadExcel() {
        this.upload.open = true
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        if (response.code != 200) {
          this.msgError(response.msg)
          return
        }
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()

        this.priceList = []
        let priceAll = response.index

        for (let i = 0; i < priceAll.length; i++) {
          priceAll[i].rowNumber = i + 1
        }
        this.form.priceAll = priceAll
        this.total = this.form.priceAll.length
        this.getPriceList()
        this.msgSuccess('导入成功')
      },
      // 提交上传文件
      submitExcelFileForm() {
        this.$refs.upload.submit()
      },
      // 前端工程量分页
      getPriceList() {
        this.priceList = this.form.priceAll.slice(
          (this.queryParams.currPage - 1) * this.queryParams.pageSize,
          this.queryParams.currPage * this.queryParams.pageSize
        )
      },
      // 提交合同
      handleContract() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.oper === 'add') {
              this.form.contractPeriod = this.form.dateRange.join('/')
              this.form.projectList = this.priceList
              addContract(this.form).then((response) => {
                this.msgSuccess('新增成功')
                this.$bus.$emit('contract-update')
                this.$closeView(this.$route, '/system/contract')
              })
            } else if (this.oper === 'update') {
              this.form.contractPeriod = this.form.dateRange.join('/')
              if (this.priceList.length > 0) {
                this.form.projectList = this.priceList
              }
              updateContract(this.form).then((response) => {
                this.msgSuccess('修改成功')
                this.$bus.$emit('contract-update')
                // ! 关闭当前标签
                this.$closeView(this.$route, '/system/contract')
              })
            }
          }
        })
      }
    },
    filters: {
      rounding(value) {
        value = value + ""

        if (value.length) {
          let index = value.indexOf(".")
          if (index < 0) {
            value = value + ".00"
          } else {
            if (index === value.length - 1) {
              value = value + "00"
            } else if (index === value.length - 2 ) {
              value = value + "0"
            } else if (index === value.length - 3) {
              value = value
            } else {
              value = value.substring(0, index + 3)
            }
          }
        } else {
          value = "0.00"
        }

        return value
      }
    }
  }
</script>
